package communicationMessages;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map.Entry;
import java.util.Vector;
import java.util.logging.Level;

import logger.LoggerWriter;

import data.Forum;
import data.MemberDataBase;
import data.SubForum;
import data.ThreadMessage;
import database.DB;

public class ViewSubForumMessage extends Message {

	@Override
	public String getAnswer() {
		LoggerWriter logger = LoggerWriter.getLoggerWriter();
		String ans="ThreadsList"+delimiter;
		System.out.println(this.content);
		String arr[] = this.content.split(delimiter);
		if (arr.length != 2)
		{
			logger.log("wrong format ViewSubForumMessage", Level.WARNING);
			ans = "wrong format ViewSubForumMessage";
			
		}
		else
		{
			try
			{
				String subForumID = arr[1];
				String userName = arr [0];
				
				ans = getViewSubForumMsg(logger, ans, subForumID, userName,true);
			}
			catch (SQLException e) {
				System.out.println(e.getMessage());
			}
		}
		return ans;
	}

	public static String getViewSubForumMsg(LoggerWriter logger, String ans,
			String subForumID, String userName,boolean changePath) throws SQLException {
		Vector <String> path = new Vector<String>();
		if (!DB.isSubForumExist(subForumID))
		{
			logger.log("the number is " + subForumID + delimiter + subForumID, Level.WARNING);
			ans = "pathNotFound" + delimiter;
			return ans;
		}
		path.add(subForumID);
		ans += DB.getUserRoll(userName,path)+delimiter;
		ans = getThreadList(ans, subForumID);
		if (changePath)
			changeCurrentPath(Integer.parseInt(subForumID), Thread.currentThread().getId());
		return ans;
	}

	private static String getThreadList(String ans, String numberOfSubForum) throws SQLException {
		ResultSet res = DB.getThreadsList(numberOfSubForum);
		while (res.next()) {
			
			ans+=res.getString(DB.threads.threadId.ordinal()) + ":" + res.getString(DB.threads.threadTitle.ordinal()) + delimiter;
		}
		return ans;
	}
	
//	else
//	{
//		String numberOfSubForum = arr[1];
//		String userName = arr [0];
//		
//		Integer subForumNumberInteger = Integer.valueOf(numberOfSubForum);
//		Vector <Integer> path = new Vector<Integer>();
//		SubForum tSubForum = Forum.getForum().getSubForum(subForumNumberInteger);
//		if (tSubForum == null)
//		{
//			logger.log("the number is " + numberOfSubForum + delimiter + subForumNumberInteger, Level.WARNING);
//			ans = "pathNotFound" + delimiter;
//			return ans;
//		}
//		path.add(subForumNumberInteger);
//		ans += MemberDataBase.getUserRoll(userName,path)+delimiter;
//		for (Entry<Integer, ThreadMessage> tEntry : tSubForum.get_messages().entrySet()) {
//			
//			ans+=tEntry.getKey() + ":" + tEntry.getValue().get_title() + delimiter;
//		}
//	}

}
